package storage;

import java.io.*;

/**
 * Class to be implemented to make objects persistent
 * 
 * @author Marcelo Gatto
 */
public abstract class Persistent {

	// Unique RecordStore ID - read-only, auto defined
	private int id = -1;

	/**
	 * Called to persist an object.
	 */
	protected byte[] persist(int rmsId) throws IOException {
		if(rmsId>0) this.id = rmsId;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		DataOutputStream dout = new DataOutputStream(bout);
		dout.writeInt(id);
		writeObject(dout);
		dout.close();
		return bout.toByteArray();
	}
	
	/**
	 * Overwrite to write specific attributes object
	 * @param dout DataOutput to write values
	 * @throws IOException
	 */
	public abstract void writeObject(DataOutput dOut) throws IOException;

	/**
	 * Called to resurrect a persistent object.
	 */
	protected void resurrect(byte[] data) throws IOException {
		ByteArrayInputStream bin = new ByteArrayInputStream(data);
		DataInputStream din = new DataInputStream(bin);
		id = din.readInt();
		readObject(din);
		din.close();
	}
	
	/**
	 * Overwrite to read specific attributes object
	 * @param dIn DataInput for read values
	 * @throws IOException
	 */
	public abstract void readObject(DataInput dIn) throws IOException;

	public int getId() {
		return id;
	}
	
}